<?php
declare (strict_types = 1);

namespace app\tools;

use app\facade\OssFacade;
use app\facade\StringFacade;
use think\facade\Filesystem;
use think\file\UploadedFile;

final class UploadTool
{
    /**
     * local 上传单个文件
     *
     * @param $uploadPath
     * @param UploadedFile $file
     * @param string $rule
     * @param bool $as 保留原文件名
     * @return string
     */
    public function upload($params, $file, $as = false, $rule = 'date(Ymd)')
    {
        $hashKey = md5((string) microtime(true));
        $path = config('app.app_name') . DIRECTORY_SEPARATOR . date('Ymd') . DIRECTORY_SEPARATOR
            . $params['type'];

        if ($as) {
            // 保留原名
            $filename = $hashKey . '_ori_' . $file->getOriginalName();
        } else {
            $filename = $hashKey . '.' . $file->getOriginalExtension();
        }

        $path = Filesystem::disk('public')->putFileAs($path, $file, $filename);

        $domain = config('domain.api');
        return $domain . config('filesystem.disks.public.url') . DIRECTORY_SEPARATOR . $path;
    }

    /**
     * 单个文件删除
     *
     * @param $path
     * @return bool
     */
    public function unlink($path)
    {
        // 获取api域名
        $domainApi = config('domain.api');
        // 兼容旧数据删除
        if (mb_strstr($path, $domainApi)) {
            $link = public_path() . str_replace($domainApi, '', $path);
            $result = @unlink($link);
        } else {
            // oss删除
            $path = StringFacade::replaceOssRelativePath($path);
            $result = OssFacade::deleteObject($path);
        }

        return $result;
    }

    /**
     * oss 上传单个文件
     *
     * @param $params
     * @param $file
     * @param false $as
     * @return string
     */
    public function ossUploadFile($params, $file, $as = false)
    {
        $hashKey = md5((string) microtime(true));
        $key = config('app.app_name') . DIRECTORY_SEPARATOR . date('Ymd') . DIRECTORY_SEPARATOR
        // $key = 'yxl' . DIRECTORY_SEPARATOR . date('Ymd') . DIRECTORY_SEPARATOR // debug
            . $params['type'] . DIRECTORY_SEPARATOR . $hashKey;

        if ($as) {
            // 保留原名
            $key .= '_ori_' . $file->getOriginalName();
        } else {
            $key .= '.' . $file->getOriginalExtension();
        }

        // 返回oss查看地址
        $showUrl = config('oss.domain'); // 显示资源域名
        return $showUrl . OssFacade::uploadFile($key, $file->getRealPath());
    }

    // /**
    //  * oss 单个文件删除
    //  *
    //  * @param $path
    //  * @return bool
    //  */
    // public function ossUnlink($path)
    // {
    //     // 获取api域名
    //     $domainApi = config('domain.api');
    //     // oss删除
    //     $path = StringFacade::replaceOssRelativePath($path);
    //     return OssFacade::deleteObject($path);
    // }
}
